const express = require("express");
const multer = require('multer');
const fs =require('fs');
const path = require('path');
const router = express.Router();
const pool = require("../pool.js");
const utils = require("../utils/index.js");
const request = require('request')
const {systemSettings} =require("../utils/menuString");
const APP_URL = 'https://api.weixin.qq.com/sns/jscode2session'
const { v4: uuidv4 } = require('uuid');
const dayjs = require('dayjs');




//小程序相关

/**
 * @swagger
 * /syn/getOpenid:
 *   post:
 *     tags:
 *       - 小程序-主页
 *     summary: 授权/获取openid
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *     responses:
 *       1:
 *         description: 成功
 *       -1:
 *         description: 失败
 */
router.post('/getOpenid', (req, res) => {
  console.log(777,req.body);
    const js_code = req.body.code
    const ART_APP_ID = systemSettings.wxpay.APPID//AppID(小程序ID)
    const ART_APP_SECRET =systemSettings.wxpay.ART_APP_SECRET //AppSecret(小程序密钥)	
    if (js_code) {
      request(`${APP_URL}?appid=${ART_APP_ID}&secret=${ART_APP_SECRET}&js_code=${js_code}&grant_type=authorization_code`, (error, response, body) => {
        if (error) throw error
        if (response.statusCode === 200) {
          const bodyInfo = JSON.parse(body)
          console.log(1234,bodyInfo);
          const openId = bodyInfo.openid
          console.log(8989,openId);
          res.send(utils.returnData({data: openId}));
        } else {
            return res.send(utils.returnData({code: -1,err,req}));
        }
      })
    }
  })

  router.post('/getUserPhone', (req, res) => {
  console.log(777,req.body);
    const js_code = req.body.code
    const ART_APP_ID = systemSettings.wxpay.APPID//AppID(小程序ID)
    const ART_APP_SECRET =systemSettings.wxpay.ART_APP_SECRET //AppSecret(小程序密钥)	
    if (js_code) {
      request(`${APP_URL}?appid=${ART_APP_ID}&secret=${ART_APP_SECRET}&js_code=${js_code}&grant_type=authorization_code`, (error, response, body) => {
        if (error) throw error
        if (response.statusCode === 200) {
          const bodyInfo = JSON.parse(body)
          var sessionKey = bodyInfo.session_key
          var pc = new WXBizDataCrypt(ART_APP_ID, sessionKey)
          var data =pc.decryptData(req.body.encryptedData, req.body.iv)
          data.openId=bodyInfo.openid;
          res.send(utils.returnData({data: data}));
        } else {
            return res.send(utils.returnData({code: -1,err,req}));
        }
      })
    }
  })


/**
 * @swagger
 * /syn/product/list:
 *   post:
 *     tags:
 *       - 小程序-权益
 *     summary: 权益列表
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *     responses:
 *       1:
 *         description: 成功
 *       -1:
 *         description: 失败
 */
 router.post("/product/list", async (req, res) => {
  let obj=req.body;
  console.log(99889,obj); 
  let sql = `SELECT  id,sku_name,price,orinprice,detail1,detail2,detail3,detail4,detail5,detail6,detail7,detail8,inventory  FROM product  `;
  pool.query(sql, [],(err, result) => {
      if (err) return res.send(utils.returnData({code: -1,err,req}));
      res.send(utils.returnData({data: result}));
  });

});
router.post("/product/detailById", async (req, res) => {
  let obj=req.body;
  console.log(99889,obj); 
  let sql = `SELECT  id,sku_name,price,orinprice,detail1,detail2,detail3,detail4,detail5,detail6,detail7,detail8,inventory  FROM product  WHERE id = "${obj.id}" `;
  pool.query(sql, [],(err, result) => {
      if (err) return res.send(utils.returnData({code: -1,err,req}));
      res.send(utils.returnData({data: result}));
  });
})




 router.post("/order/list", async (req, res) => {
  let obj=req.body;
  let sql = `SELECT a.id, a.source, a.order_id as orderId, a.phone, a.receive_time AS receiveTime, a.ext_code as extCode, a.quantity AS quantity, a.rights_id as rightsid, a.price, a.sku_id as skuId, a.sku_code as skuCode, a.sku_name AS skuName,  a.user_consignee_id, a.express_company, a.tracking_number AS trackingNumber, a.state AS state, a.sms_num, a.create_time AS createTime, a.update_time as updateTime, a.created_at,a.user_consignee_name AS consigneeName,a.user_consignee_phone AS consigneePhone,a.user_consignee_address  AS  address FROM t_order a left join t_user_consignee b  on a.user_consignee_id=b.id WHERE a.phone ="${obj.phone}"  and a.source='来伊份'  and (a.state=1 or a.state=2 )  and a.sku_code like 'lyf0%'   ORDER BY a.update_time DESC `;
  pool.query(sql, [obj.phone],(err, result) => {
      if (err) return res.send(utils.returnData({code: -1,err,req}));
      res.send(utils.returnData({data: result}));
  });

});


module.exports = router;
